from django.shortcuts import render
from rest_framework.views import APIView
from random import randint
import logging
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status

from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
from . import constans

logger = logging.getLogger('django')


# Create your views here.
class SMSCodeView(APIView):
    """短信验证码"""

    def get(self, request, mobile):
        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        # 先从redis获取此手机号发送短信标记
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:  # 如果此手机号在60秒内发过短信提前响应不执行后续发短信代码
            return Response({'message': '频繁发送验证码'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)

        # # 利用容联云通讯SDK 发送验证码
        # # CCP().send_template_sms(self, to, datas, temp_id):
        # CCP().send_template_sms(mobile, [sms_code, constans.SMS_CODE_REDIS_EXPIRES // 60], constans.SMS_CODE_TEMPLATE_ID)

        # 触发celery异步任务
        # send_sms_code(mobile, sms_code)  # 千万不能这样写,这样和执行一个普通函数没区别
        send_sms_code.delay(mobile, sms_code)  # 异步任务函数名.delay(参数) 这样才会触发celery异步任务

        # 创建redis管道对象
        pl = redis_conn.pipeline()
        # 把验证码存储到redis
        # redis_conn.setex('sms_%s' % mobile, constans.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constans.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 给发送过短信的手机号存储一个已发送标记
        # redis_conn.setex('send_flag_%s' % mobile, constans.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' % mobile, constans.SEND_SMS_CODE_INTERVAL, 1)
        # 执行管道
        pl.execute()
        # 响应
        return Response({'message': 'ok'})
